//
//  BackgroundLayer.m
//  SCRAP_ObjC
//
//  Created by Capstone Design Fall 2010 on 10/18/10.
//  Copyright 2010 Thunderwear. All rights reserved.
//

#import "BackgroundLayer.h"
#import "Card.h"
#import "CardData.h"
#import "StackAdditions.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MenuLayer.h"
#import "Constants.h"
#import "SimpleAudioEngine.h"
#import "CDAudioManager.h"
#import "CocosDenshion.h"
#import "SoundPlayer.h"

#define zBackground 0
#define zCards 1
#define zOverlay 2
#define shadowTag 0
#define stockBackScale 0.7f


@implementation BackgroundLayer

- (void) update:(ccTime)dt {
	Card *blank = [[Card alloc] initWithRank:5 withSuit:'h'];
	[gameSession sendCard:blank];
	[blank release];
}

- (id) init
{
	if( (self = [super init]))
	{
		[SoundPlayer loadSound:@"card_send.aif"];
		//gamePeerId = nil;
		isMoving=FALSE;
		isLocked=FALSE;
		size = [[CCDirector sharedDirector] winSize];
		center = ccp(size.width / 2, size.height / 2);
		
		background = [[CCSprite spriteWithFile: @"clear_iPhone_bkgr.png"] retain];
		portal = [[CCSprite spriteWithFile:@"grey_phone_portal.png"] retain];
		[portal setPosition:ccp(center.x-45, size.height-[portal boundingBox].size.height/2)];
		portal.scaleX = 1.2;
		
		lockLayer = [[CCColorLayer layerWithColor:ccc4(128, 128, 128, 0)] retain];
		messageLabel = [[CCLabel labelWithString:@"Card on Public Display..." fontName:SCRAPFont fontSize:36] retain];
		scoreLabel = [[CCLabel labelWithString:@"" fontName:SCRAPFont fontSize:36] retain];
		cardsLeft = [[CCLabel labelWithString:[NSString stringWithString:@"13"] fontName:SCRAPFont fontSize:20] retain];
		reserveBack = [[CCSprite spriteWithFile:@"empty_back.png"] retain];
		reserveBack.scale = iPhoneScale;
		stockBack = [[CCSprite spriteWithFile:@"empty_back.png"] retain];
		stockBack.scale = stockBackScale;
		
		[messageLabel setColor:ccc3(255, 255, 255)];
		[messageLabel setPosition:ccp(size.width*2, size.height/2)];		
		
		[scoreLabel setColor:ccc3(255, 255, 255)];
		[scoreLabel setPosition:ccp(size.width*2, size.height/2 - 30)];
		
		CCLabel * nameLogo = [CCLabel labelWithString:@"SCRAP" fontName:SCRAPFont fontSize:18];
		nameLogo.opacity = 128;
		[nameLogo setColor:ccc3(80, 80, 80)];
		[nameLogo setPosition:ccp(35,10)];		
		
		[background setPosition:ccp(size.width / 2, size.height / 2)];
		
		[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
		
		Card * card = [Card initWithRank:2 withSuit:'s' forIPhone:nil];
		cardHeight = [card boundingBox].size.height;
		cardWidth = [card boundingBox].size.width;
		[card release];
		
		// alloc all points
		wastePoints = [[NSMutableArray alloc] init];
		cascadePoints = [[NSMutableArray alloc] init];
		
		[self addChild:background z:zBackground];
		
		// set up points for each card location
		for (float i=0; i<5; i++) {
			if (i<4) {				
				CGPoint p = ccp(68+i*82, size.height-100);
				CCSprite * cOutline = [CCSprite spriteWithFile:@"glow_contour.png"];
				[cOutline setPosition:p];
				cOutline.scale = iPhoneScale;
				[self addChild:cOutline z:zBackground];
				[cascadePoints addObject:[[FPoint alloc] initWithCGPoint:p]];
				
			} else {
				reservePoint = ccp(94+i*80, size.height-76);
				CCSprite * rOutline = [CCSprite spriteWithFile:@"reserve_contour.png"];
				rOutline.scale = iPhoneScale;
				[rOutline setPosition:ccp(reservePoint.x, size.height - [rOutline boundingBox].size.height/2)];
				[self addChild:rOutline z:zBackground];
				stockPoint = ccp(i*size.width/5+30, size.height-176);
				CCSprite * sOutline = [CCSprite spriteWithFile:@"glow_contour.png"];
				[sOutline setPosition:stockPoint];
				sOutline.scale = stockBackScale;
				[self addChild:sOutline z:zBackground];
				
				for (int j=0; j<3; j++) {
					[wastePoints push:[[FPoint alloc] initWithCGPoint:ccp(i*size.width/6+60 + 30*j, cardHeight/2 + 1)]];
				}
			}
		}
		
		[self addChild:nameLogo z:zBackground];
		[self addChild:portal z:zBackground];
		[self addChild:lockLayer z:zOverlay];	// setting to 1 gives it a higher position than all other 0-default sprites
		[self addChild:messageLabel z:zOverlay]; // just higher than lockLayer
		[self addChild:scoreLabel z:zOverlay];
		
		//[self schedule: @selector(update:) interval: 1.0f/60.0f];
		
		isPlaying = false;
		touchedStock = false;
		hasPlayedWaste = false;
		//[self startRound];
		//[gameSession startPicker];
		active = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
	}
	
	return self;
}

-(void) startRound {
	isPlaying=true;
	isLocked = false;
	isMoving = false;
	gameSession.GameOver = false;
	
	// Clear data from previous rounds, if necessary
	if (cardData != nil) {
		[self resetAssets];
		[cardData release];
	}
	cardData = [[CardData alloc] initGameWithSize:size];
	
	float easeTime = 0.75f;	
	
	NSString * numCardsLeft = [NSString stringWithFormat:@"%i", [cardData.reserve count]];
	[cardsLeft setString:numCardsLeft];
	cardsLeft.opacity = 0;
	[cardsLeft setPosition:ccp(reservePoint.x, size.height-16)];
	[cardsLeft runAction:[CCFadeTo actionWithDuration:easeTime opacity:255]];	
	[self addChild:cardsLeft];
	
	// cascades
	for (int i=0; i<4; i++) {		
		NSMutableArray * cascade = [cardData.cascades objectAtIndex:i];
		FPoint * cascadePoint = [cascadePoints objectAtIndex:i];
		Card * card = [cascade top];
		
		CGPoint new = ccp(cascadePoint.x, cascadePoint.y);
		CGPoint old = ccp(cascadePoint.x, size.height+ cardHeight/2);
		card.position = old;
		card.holdPos = new;
		id action = [CCMoveTo actionWithDuration:easeTime position:new];
		id ease = [CCEaseExponentialOut actionWithAction:action];
		[card runAction:ease];
		[card setShadow:cardIdleShadow];
		[self addChild:card];
	}
	
	// reserve
	CGPoint new = ccp(reservePoint.x, reservePoint.y);
	CGPoint old = ccp(reservePoint.x, size.height+cardHeight/2);
	
	id action = [CCMoveTo actionWithDuration:easeTime position:new];
	id ease = [CCEaseExponentialOut actionWithAction:action];
	reserveBack.position = old;
	[reserveBack runAction:ease];
	[self addChild:reserveBack];
	
	action = [CCMoveTo actionWithDuration:easeTime position:new];
	ease = [CCEaseExponentialOut actionWithAction:action];
	Card * card = [cardData.reserve top];
	card.position = old;
	card.holdPos = new;
	[card runAction:ease];
	[self addChild:card];
	
	// stock
	old = ccp(size.width + cardWidth/2, stockPoint.y);
	new = ccp(stockPoint.x, stockPoint.y);
	action = [CCMoveTo actionWithDuration:easeTime position:new];
	ease = [CCEaseExponentialOut actionWithAction:action];
	stockBack.position = old;
	[stockBack runAction:ease];
	[self addChild:stockBack];
	
	//[self schedule:@selector(update:) interval:1];
	
}

// locks the screen and shows whatever is necessary
-(void) endRound {
	isPlaying = false;
	isLocked = true;
	isMoving = false;
	gameSession.GameOver = true;
	
	// Fade to gray
	id fadeAction = [CCFadeTo actionWithDuration:.3 opacity:200];	
	[lockLayer runAction:fadeAction];
	
	// Message
	[messageLabel setString:@"Round over!" ];
	id sweepAction = [CCMoveTo actionWithDuration:.3 position:center];
	id ease = [CCEaseIn actionWithAction:sweepAction rate:3];
	[messageLabel runAction:ease];
	
	// Score
	[scoreLabel setString:[NSString stringWithFormat:@"Score: %d", score]];
	sweepAction = [CCMoveTo actionWithDuration:.3 position:ccp(center.x, center.y-30)];
	ease = [CCEaseIn actionWithAction:sweepAction rate:3];
	[scoreLabel runAction:ease];
}

// moves everything off screen or fades them out to prepare for a new round
-(void) resetAssets {
	// try adding all visual assets in init and bringing them in and out here and in startRound
	
	for (Card * card in cardData.allCards) {
		if ([self.children containsObject:card]) {
			[self removeChild:card cleanup:TRUE];
		}
	}
	[self removeChild:cardsLeft cleanup:TRUE];
	[self removeChild:stockBack cleanup:TRUE];
	[self removeChild:reserveBack cleanup:TRUE];
	
	id fadeAction = [CCFadeTo actionWithDuration:.3 opacity:0];
	[lockLayer runAction:fadeAction];
	
	id sweepAction = [CCMoveTo actionWithDuration:.3 position:ccp(center.x-500, center.y)];
	id ease = [CCEaseIn actionWithAction:sweepAction rate:3];
	[messageLabel runAction:ease];
	
	sweepAction = [CCMoveTo actionWithDuration:.3 position:ccp(center.x-500, center.y-30)];
	ease = [CCEaseIn actionWithAction:sweepAction rate:3];
	[scoreLabel runAction:ease];
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
	if (isLocked || !isPlaying || isMoving) {
		return TRUE;
	}
	
	CGPoint point = [touch locationInView:[touch view]];
	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
	float x = convertedPoint.x;
	float y = convertedPoint.y;
	Card * card;
	
	// Check if they tapped the stock pile
	if(CGRectContainsPoint([stockBack boundingBox], convertedPoint))
	{
		touchedStock=true;
		return TRUE;
	}
	
	// We now know that they're trying to move a card
	// Make a list of valid cards to be moved
	NSMutableArray * possibleCards = [[NSMutableArray alloc] init];
	for (NSMutableArray * cascade in cardData.cascades) {
		for (Card * card in [cascade reverseObjectEnumerator]) {
			[possibleCards push:card];
		}
	}
	if( (card = [cardData.reserve top]) )
		[possibleCards push:card];
	if( (card = [cardData.waste top]) )
		[possibleCards push:card];
	
	for (card in possibleCards) {
		if ([card pointInside:convertedPoint])
		{
			cardData.current = card;
			card.touch = touch;
			card.touchOffset = ccp(x-card.position.x, y-card.position.y);
			isMoving = TRUE;
			break;
		}
	}
	
	if(isMoving)
	{
		// remove then add to bring to front
		NSMutableArray * stack = cardData.current.stackRef;
		
		int startGrow = [stack indexOfObject:cardData.current];
		int endGrow = [stack count]-1;
		float sizeDiff = iPhoneScaleGrowLarge - iPhoneScaleGrowSmall;
		
		id action = [CCScaleTo actionWithDuration:.25 scale:iPhoneScaleGrowLarge];
		id ease = [CCEaseElasticOut actionWithAction:action];
		[cardData.current runAction:ease];
		
		// it's in a cascade
		if ([cardData.cascades containsObject:stack])
		{
			for (int i=startGrow; i<[stack count]; i++)
			{
				Card * card = [stack objectAtIndex:i];
				[self removeChild:card cleanup:FALSE];
				[self addChild:card];
				
				float grow = 1.0f;
				float _shadow;// = 255.0f;
				
				if (i>=startGrow)
				{
					if (startGrow != endGrow)
						grow = iPhoneScaleGrowLarge - sizeDiff*((float)(i-startGrow)/(endGrow-startGrow));
					else
						grow = iPhoneScaleGrowLarge;
					
					if (i==startGrow)
						_shadow = 255;
					else
						_shadow = 100;
					
					[card setShadow:_shadow];
				}
				action = [CCScaleTo actionWithDuration:.25 scale:grow];
				ease = [CCEaseElasticOut actionWithAction:action];
				[card runAction:ease];
				
			}
		}
		// it's in waste or reserve
		else
		{
			Card * card = [cardData.current.stackRef top];
			id action = [CCScaleTo actionWithDuration:.25 scale:iPhoneScaleGrowLarge];
			id ease = [CCEaseElasticOut actionWithAction:action];
			[card runAction:ease];
			
			[card setShadow:255];
			
			[self removeChild:card cleanup:FALSE];
			[self addChild:card];
		}
	}
	return TRUE;
}

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
	if(isMoving && cardData.current.touch == touch) {
		CGPoint point = [touch locationInView:[touch view]];
		CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
		CGPoint bottomPos = ccp(convertedPoint.x-cardData.current.touchOffset.x, convertedPoint.y-cardData.current.touchOffset.y);
		[cardData.current setPosition:bottomPos];
		
		// if a cascade, move all lower cards too
		int index = [cardData.current.stackRef indexOfObject:cardData.current];
		if ([cardData.cascades containsObject:cardData.current.stackRef]) {
			for (int i=index+1; i<[cardData.current.stackRef count]; i++) {
				Card * card = [cardData.current.stackRef objectAtIndex:i];
				[card setPosition:ccp(bottomPos.x, bottomPos.y-iPhoneCardVDist*(i-index))];
			}
		}
	}
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint point = [touch locationInView:[touch view]];	
	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
	
	if(isMoving && cardData.current.touch == touch) {
		//[testCard stopAllActions];
		[cardData.current stopAllActions];
		
		for (Card * card in cardData.current.stackRef) {
			id action = [CCScaleTo actionWithDuration:.25 scale:iPhoneScale];
			id ease = [CCEaseElasticOut actionWithAction:action];
			[card runAction:ease];
		}		
	
		// if in portal
		if (convertedPoint.y > 275 && cardData.current == [cardData.current.stackRef top]
			&& gameSession.gamePeerId) {
			id action = [CCMoveTo actionWithDuration:.25 position:ccp(size.width / 2, size.height+200)];
			id ease = [CCEaseInOut actionWithAction:action];
			[cardData.current runAction:ease];
			[cardData.current.stackRef pop];
			[self startLock];
			[gameSession sendCard: cardData.current];
			//play sound here
			[SoundPlayer playSound:CARDSENDSOUND];
			
		} else {
			// check if they put it on a cascade
			CGRect curRect = [cardData.current boundingBox];
			NSMutableArray * cascade;
			int overlapArea = 0;
			Card * overlapCard = nil;
			int overlapCascadeIndex=0;
			bool isEmptySlot=false;
			for (int i=0; i<4; i++) {
				cascade = [cardData.cascades objectAtIndex:i];
				Card * checkCard = [cascade top];
				
				// checking empty slot
				if(!checkCard) {
					FPoint * cascCenter = [cascadePoints objectAtIndex:i];
					CGRect checkRect = CGRectMake(cascCenter.x-cardWidth/2, cascCenter.y-cardHeight/2, cardWidth, cardHeight);
					if (CGRectIntersectsRect(curRect, checkRect)) {
						CGRect interRect = CGRectIntersection(curRect, checkRect);
						int area = interRect.size.width*interRect.size.height;
						if (area>overlapArea) {
							overlapArea = area;
							overlapCascadeIndex = i;
							isEmptySlot = true;
						}
					}
				}
				// checking card on cascade
				else {
					CGRect checkRect = [checkCard boundingBox];
					if(checkCard && CGRectIntersectsRect(curRect, checkRect) && checkCard != cardData.current && cardData.current.rank == checkCard.rank-1 &&
					   ( ([cardData.current isRed] && [checkCard isBlack]) || ([cardData.current isBlack] && [checkCard isRed]) ) )
					{
						CGRect interRect = CGRectIntersection(curRect, checkRect);
						int area = interRect.size.width*interRect.size.height;
						if (area>overlapArea) {
							overlapArea = area;
							overlapCard = checkCard;
							isEmptySlot = false;
						}
					}
				}
			}
			
			// we found a maximally overlapping card, move stuff
			if(overlapArea) {
				NSMutableArray * floating = [cardData.current.stackRef popFrom:cardData.current];
				[self handleFlipReserve];
				CGPoint topPoint;
				
				if (cardData.current.stackRef == cardData.waste) {
					hasPlayedWaste = true;
				} else if (cardData.current.stackRef == cardData.reserve) {
					[gameSession updateReserveCount: [cardData.reserve count]];
				}
				
				if (isEmptySlot) {					
					topPoint = [[cascadePoints objectAtIndex:overlapCascadeIndex] toCGPoint];
					cascade = [cardData.cascades objectAtIndex:overlapCascadeIndex];
					
				} else {
					topPoint = ccp(overlapCard.position.x, overlapCard.position.y - iPhoneCardVDist);					
					cascade = overlapCard.stackRef;
				}
				
				for (int i=0; i<[floating count]; i++) {
					Card * card = [floating objectAtIndex:i];
					card.holdPos = ccp(topPoint.x, topPoint.y - i*iPhoneCardVDist);
					card.stackRef = cascade;
				}

				[cardData.current.stackRef addObjectsFromArray:floating];
				[floating release];
			}
			
			// We're moving a list of cards
			if ([cardData.cascades containsObject:cardData.current.stackRef]) {
				for (Card * card in cardData.current.stackRef) {
					id action = [CCMoveTo actionWithDuration:.3 position:card.holdPos];
					id ease = [CCEaseExponentialOut actionWithAction:action];
					[card runAction:ease];
					
					[card setShadow:cardIdleShadow];
				}
			}
			// We're only moving one card
			else {
				id action = [CCMoveTo actionWithDuration:.3 position:cardData.current.holdPos];
				id ease = [CCEaseExponentialOut actionWithAction:action];
				[cardData.current runAction:ease];
				
				[cardData.current setShadow:cardIdleShadow];
			}
			
			cardData.current = nil;			
		}
	} else if (touchedStock && CGRectContainsPoint([stockBack boundingBox], convertedPoint)) {
		[self drawCards];
	}
	//for now, check to see if clicked bottom left corner to "return card"
	else if (convertedPoint.x<20 && convertedPoint.y<20) {
		//[self cardReturned];
		//[self startLock];
		// [[CCDirector sharedDirector] replaceScene:[MenuLayer scene]];
	}
	
	touchedStock=false;	
	isMoving = FALSE;
}

- (void) handleFlipReserve {
	// assumes card has already been popped from the reserve
	if ([cardData.current stackRef] == cardData.reserve) {
		if ([cardData.reserve count]>0) {
			Card * card = [cardData.reserve top];
			card.opacity = 0;
			card.position = reservePoint;
			card.holdPos = card.position;
			id action = [CCFadeTo actionWithDuration:.2 opacity:255];
			[card runAction:action];
			[self addChild:card];
			
			if ([cardData.reserve count] == 1) {
				[reserveBack runAction:[CCFadeTo actionWithDuration:.3 opacity:0]];				
			}
			
			[cardsLeft setString:[NSString stringWithFormat:@"%d", [cardData.reserve count]]];
		}
	}
}

- (void) drawCards {
	if (![cardData.stock isEmpty]) {
		// move cards under right side
		for (Card * card in cardData.waste) {
			[card stopAllActions];
			CGPoint point = [[wastePoints objectAtIndex:0] toCGPoint];
			id action = [CCMoveTo actionWithDuration:.2 position:point];
			id ease = [CCEaseExponentialOut actionWithAction:action];
			[card runAction:ease];
			[card removeShadow];
		}
		
		// draw up to 3 cards
		for (int i=0; i<3 && ![cardData.stock isEmpty]; i++) {
			Card * card = [cardData.stock pop];
			[cardData.waste push:card];
			card.stackRef = cardData.waste;
			card.position = stockPoint;
			CGPoint point = [[wastePoints objectAtIndex:i] toCGPoint];
			card.holdPos = point;
			card.opacity = 0;
			
			id actionMove = [CCMoveTo actionWithDuration:.2 position:point];
			id ease1 = [CCEaseExponentialOut actionWithAction:actionMove];
			id actionFade = [CCFadeTo actionWithDuration:.1 opacity:255];
			id ease2 = [CCEaseOut actionWithAction:actionFade rate:2];
			[card runAction:[CCSpawn actions: ease1, ease2, nil]];
			[card setShadow:cardIdleShadow];
			[self addChild:card];
		}
		
		if ([cardData.stock isEmpty]) {
			id fadeAction = [CCFadeTo actionWithDuration:.2 opacity:0];
			[stockBack runAction:fadeAction];
			
			[[stockBack getChildByTag:746] runAction:[CCTintTo actionWithDuration:.2 red:255 green:255 blue:255]];
		}
	} else {
		while(![cardData.waste isEmpty]) {
			Card * card = [cardData.waste pop];
			[card stopAllActions];
			[self removeChild:card cleanup:false];
			[cardData.stock push:card];
			card.stackRef = cardData.stock;
		}
		
		// Move top to bottom if they didn't play any cards that set
		if (!hasPlayedWaste) {
			Card * card = [cardData.stock pop];
			[cardData.stock insertObject:card atIndex:0];
		}
		[stockBack stopAllActions];
		id fadeAction = [CCFadeTo actionWithDuration:.2 opacity:255];
		[stockBack runAction:fadeAction];
		[[stockBack getChildByTag:746] runAction:[CCTintTo actionWithDuration:.2 red:_color.r green:_color.g blue:_color.b]];
	}
	
	hasPlayedWaste=false;
}

- (void) startLock {
	isLocked=true;
	
	id fadeAction = [CCFadeTo actionWithDuration:.3 opacity:200];	
	[lockLayer runAction:fadeAction];
	
	[messageLabel setString:@"Card on Public Display..."];
	[messageLabel setPosition:ccp(center.x+500, center.y)];
	id sweepAction = [CCMoveTo actionWithDuration:.3 position:center];
	id ease = [CCEaseIn actionWithAction:sweepAction rate:3];
	[messageLabel runAction:ease];
}

- (void) stopLock
{
	isLocked=FALSE;
	
	id fadeAction = [CCFadeTo actionWithDuration:.3 opacity:0];
	[lockLayer runAction:fadeAction];
	
	id sweepAction = [CCMoveTo actionWithDuration:.3 position:ccp(center.x-500, center.y)];
	id ease = [CCEaseIn actionWithAction:sweepAction rate:3];
	[messageLabel runAction:ease];
}

- (void) setScore:(int)n {
	score = n;
}

- (void) cardAccepted
{
	[self stopLock];
		
	[self handleFlipReserve];
	
	[self removeChild:cardData.current cleanup:TRUE];
	
	if (cardData.current.stackRef == cardData.reserve) {
		[gameSession updateReserveCount: [cardData.reserve count]];
	}
	cardData.current = nil;
	
}

-(void) cardReturned
{
	//play sound
//	[SoundPlayer playSound:@"card_send" withType:@"wav"];
	[SoundPlayer playSound:CARDSENDSOUND];
	// TODO: return the card to its original position in the private display
	[self stopLock];
	[cardData.current.stackRef push:cardData.current];
	
	[cardData.current setShadow:cardIdleShadow];
	
	[cardData.current setPosition:ccp(center.x, size.height + cardHeight/2)];
	id action = [CCMoveTo actionWithDuration:.3 position:cardData.current.holdPos];
	id ease = [CCEaseExponentialOut actionWithAction:action];
	[cardData.current runAction:ease];
	cardData.current = nil;
}

- (void) dealloc
{
	NSLog(@"Deallocating BG Layer\n");
	
	// cleanup the session
	[gameSession invalidateSession];
	[gameSession release];
	[background release];
	[lockLayer release];
	[messageLabel release];
	[scoreLabel release];
	[cardsLeft release];
	[reserveBack release];
	[stockBack release];
	
	[super dealloc];
}

-(void)showError: (NSString*)msg
{
	[self vibrate];
	/*UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Rejected" message:msg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
	[alert show];
	[alert release];*/
}

- (void)vibrate {
	AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}

- (NSString *) append:(NSArray*) array
{
    NSString *result = @"";
    for (int i = 0; i< [array count]; i++) {
		result = [result stringByAppendingString:[array objectAtIndex:i]];
		result = [result stringByAppendingString:@" "];
	}    
	return result;
}


////////////////NETWORKING------CURRENT WORKING PEER-PEER/////////////////////
-(void) setPicker:(iPhoneSession*)sesh
{
	gameSession = [sesh retain];
	gameSession.gameDelegate = self;
	[gameSession startPicker];
	[[[CCDirector sharedDirector] openGLView] addSubview: active];
	active.center = ccp(size.height/4, size.width/2);
	[active startAnimating];
}

-(void)session:(iPhoneSession*)sesh stopAnimation:(BOOL*)ans
{
	if (ans == YES) {
		[active stopAnimating];
	}
}

-(void)session:(iPhoneSession*)sesh didReceiveMessage:(NSString*)aStr
{
	NSMutableArray *ras = [aStr componentsSeparatedByString:@  " "];
	if ([[ras objectAtIndex:0] isEqualToString:@"StartRound"]) {
		[self startRound];
	}
	else if ([[ras objectAtIndex:0] isEqualToString:@"EndRound"]) {
		int newScore = [[ras objectAtIndex:1] intValue];
		[self setScore: newScore];
		[self endRound];
	}
	else if ([[ras objectAtIndex:0] isEqualToString:@"Rejected"]) {
		[ras removeObjectAtIndex:0];
		NSString *err = [self append:ras];
		[self showError:err];
	}
	else if ([[ras objectAtIndex:0] isEqualToString:@"Color"]){
		colorName = [[NSString stringWithString:[ras objectAtIndex:1]] retain];
		//[self removeChild:background cleanup:YES];
		//[background release];
		//background = [[CCSprite spriteWithFile: BGstring] retain];
		//[background setPosition:ccp(size.width / 2, size.height / 2)];
		//[self addChild:background z:-1];
		CCSprite *pattern1, *pattern2;		
		pattern1 = [CCSprite spriteWithFile:@"card_pattern.png"];
		pattern2 = [CCSprite spriteWithFile:@"card_pattern.png"];
		if ([colorName isEqualToString:@"blue"]) {
			_color = portal.color = pattern1.color = pattern2.color = BLUE;			
		} else if ([colorName isEqualToString:@"red"]) {
			_color = portal.color = pattern1.color = pattern2.color = RED;
		} else if ([colorName isEqualToString:@"purple"]) {
			_color = portal.color = pattern1.color = pattern2.color = PURPLE;
		} else if ([colorName isEqualToString:@"yellow"]) {
			_color = portal.color = pattern1.color = pattern2.color = YELLOW;
		}
		
		[pattern1 setPosition:ccp([reserveBack boundingBox].size.width/2/iPhoneScale, [reserveBack boundingBox].size.height/2/iPhoneScale)];	 
		[pattern2 setPosition:ccp([stockBack boundingBox].size.width/2/stockBackScale, [stockBack boundingBox].size.height/2/stockBackScale)];
		[reserveBack addChild:pattern1 z:0 tag:746];
		[stockBack addChild:pattern2 z:0 tag:746];
	}
	else if([[ras objectAtIndex:0] isEqualToString:@"Accepted"]) {
		[self cardAccepted];
	}
	else if([[ras objectAtIndex:0] isEqualToString:@"Return"]){
		[self cardReturned];
	}
	else if([[ras objectAtIndex:0] isEqualToString:@"EndGame"]){
		[gameSession invalidateSession];
		[[CCDirector sharedDirector] replaceScene:[CCFadeTRTransition transitionWithDuration:1 scene:[MenuLayer scene]]];
		// [[CCDirector sharedDirector] replaceScene:[MenuLayer scene]];
	}
	
}

@end
